package singleton;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author liouwb
 * 单例模式
 * 饿汉式
 */
public class SingletonHungryTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 饿汉式
        SingletonHungry hungry = SingletonHungry.getInstance();
        SingletonHungry hungry1 = SingletonHungry.getInstance();

        // 通过反射实例
        Class<SingletonHungry> hungryClass = SingletonHungry.class;
        Constructor<SingletonHungry> constructor = hungryClass.getDeclaredConstructor();

        constructor.setAccessible(true);
        SingletonHungry hungry2 = constructor.newInstance();


        // 验证单例是否全局只有一个实例
        System.out.println("饿汉式正常获取的实例比较：" + (hungry == hungry1));
        // 正常获取实例与反射获取实例对比
        System.out.println("饿汉式正常获取的实例与反射获取实例比较：" + (hungry == hungry2));

        // 输出对象信息
        System.out.println("hungry ：" + hungry);
        System.out.println("hungry1：" + hungry1);
        System.out.println("hungry2：" + hungry2);
    }

    /**
     * 饿汉式
     */
    static class SingletonHungry {
        private static SingletonHungry instance = new SingletonHungry();

        /**
         * 构造函数
         *
         * @return
         */
        private SingletonHungry() {
        }

        /**
         * @return
         */
        public static SingletonHungry getInstance() {

            return instance;
        }
    }
}
